package main

import (
	"fmt"
	"html/template"
	"log"
	"os/exec"
	"reflect"
	"time"

	// "github.com/gin-contrib/sessions"
	// "github.com/gin-contrib/sessions/cookie"
	"github.com/gin-contrib/timeout"
	"github.com/gin-gonic/gin"
)

// 模板函数
func defaultTplValue(def interface{}, val interface{}) interface{} {
	// 检查 val 是否为空值
	if val == nil || (reflect.ValueOf(val).Kind() == reflect.String && val == "") {
		return def
	}
	return val
}

// 超时控制
func killProcess(pid any) error {
	cmd := exec.Command("kill", fmt.Sprintf("%d", pid))
	err := cmd.Start()
	if err != nil {
		return err
	}
	err = cmd.Wait()
	if err != nil {
		return err
	}
	return nil
}
func testResponse(c *gin.Context) {
	pid, has := c.Get("pid")
	if has {
		log.Println(pid)
		err := killProcess(pid)
		if err != nil {
			fmt.Printf("Failed to kill process: %v\n", err)
		} else {
			fmt.Printf("Process with PID %d killed successfully\n", pid)
		}
	} else {
		log.Println("pid not found")
	}
	c.String(200, "\n timeout")
}
func timeoutMiddleware() gin.HandlerFunc {
	return timeout.New(
		timeout.WithTimeout(60*time.Second),
		timeout.WithHandler(func(c *gin.Context) {
			c.Next()
		}),
		timeout.WithResponse(testResponse),
	)
}
func startHttpServer() {
	// 创建Gin的默认引擎
	r := gin.Default()
	// r.Use(gin.Recovery())
	// 设置静态文件夹
	r.Static("/", "./frontend/static")
	// 自定义分隔符
	r.Delims("~{", "}~")
	// 定义自定义函数 default
	funcMap := template.FuncMap{
		"default": defaultTplValue,
	}
	r.SetFuncMap(funcMap)
	// 设置HTML模板文件夹
	// r.LoadHTMLGlob("frontend/templates/**/*")
	// 在中间件中使用自定义的超时响应
	r.Use(timeoutMiddleware())
	// 添加路由
	route(r)

	// 启动HTTP服务器，默认监听在本地的8080端口
	r.Run(fmt.Sprintf(":%d", 9191))

	// 使用自签名证书和私钥启动 HTTPS 服务
	// r.RunTLS(":443", "ssl\\cert.pem", "D:\\code\\_go\\youdu-jielong\\src\\ssl\\key.pem")
	// r.RunTLS(fmt.Sprintf(":%d", config.Inst.Server.Port), currentDir+"/ssl/cert.pem", currentDir+"/ssl/key.pem")

	log.Println("Server started")
}
